<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="项目" prop="projectId">
          <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable filterable>
            <el-option v-for="dict in projectIdOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划号" prop="serialNo">
          <el-input v-model="queryParams.serialNo" placeholder="请输入计划号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="交货日期">
          <el-date-picker v-model="daterangeDeliveryDate" style="width: 240px" value-format="YYYY-MM-DD" type="daterange"
            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
        </el-form-item>
        <el-form-item label="申请人" prop="applyUser">
          <el-select v-model="queryParams.applyUser" placeholder="请选择申请人" clearable filterable>
            <el-option v-for="dict in applyUserOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker v-model="daterangeApplyTime" style="width: 240px" value-format="YYYY-MM-DD" type="daterange"
            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
        </el-form-item>
        <el-form-item label="申请状态" prop="applyStatus">
          <el-select v-model="queryParams.applyStatus" placeholder="请选择申请状态" clearable filterable>
            <el-option v-for="dict in applyStatusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核人" prop="auditUser">
          <el-select v-model="queryParams.auditUser" placeholder="请选择审核人" clearable filterable>
            <el-option v-for="dict in auditUserOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核时间">
          <el-date-picker v-model="daterangeAuditTime" style="width: 240px" value-format="YYYY-MM-DD" type="daterange"
            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus">
          <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable filterable>
            <el-option v-for="dict in auditStatusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-table v-loading="loading" :data="productPlanList">
        <el-table-column label="编号" align="center" prop="id" />
        <el-table-column label="计划号" align="center" prop="serialNo" />
        <el-table-column label="项目" align="center" prop="projectId" :formatter="projectIdFormat" />
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="交货日期" align="center" prop="deliveryDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请人" align="center" prop="applyUser" :formatter="applyUserFormat" />
        <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请状态" align="center" prop="applyStatus" :formatter="applyStatusFormat" />
        <el-table-column label="审核人" align="center" prop="auditUser" :formatter="auditUserFormat" />
        <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="auditStatus" :formatter="auditStatusFormat" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" link :icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['mesPlan:productPlan:audit']">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        @pagination="getList" />
  
      <!-- 添加或修改生产计划对话框 -->
      <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" :inline="true">
          <el-form-item label="计划号" prop="serialNo">
            <el-input v-model="form.serialNo" placeholder="" disabled />
          </el-form-item>
          <el-form-item label="订单号" prop="orderNo">
            <el-input v-model="form.orderNo" placeholder="请选择订单" disabled>
              <template #append>
                <el-button disabled>选择</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="项目" prop="projectId">
            <el-select v-model="form.projectId" placeholder="请选择项目" clearable filterable disabled>
              <el-option v-for="dict in projectIdOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="parseInt(dict.dictValue)" />
            </el-select>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入名称" disabled />
          </el-form-item>
          <el-form-item label="交货日期" prop="deliveryDate">
            <el-date-picker v-model="form.deliveryDate" type="date" value-format="YYYY-MM-DD" placeholder="" disabled />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" disabled />
          </el-form-item>
          <el-form-item label="申请人" prop="applyUser">
            <el-select v-model="form.applyUser" placeholder="" clearable filterable disabled>
              <el-option v-for="dict in applyUserOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="申请时间" prop="applyTime">
            <el-date-picker v-model="form.applyTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="" disabled />
          </el-form-item>
          <el-form-item label="申请状态" prop="applyStatus">
            <el-select v-model="form.applyStatus" placeholder="" clearable filterable disabled>
              <el-option v-for="dict in applyStatusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="审核人" prop="auditUser">
            <el-select v-model="form.auditUser" placeholder="" clearable filterable disabled>
              <el-option v-for="dict in auditUserOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="审核时间" prop="auditTime">
            <el-date-picker v-model="form.auditTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="" disabled />
          </el-form-item>
          <el-form-item label="审核状态" prop="auditStatus">
            <el-select v-model="form.auditStatus" placeholder="" clearable filterable disabled>
              <el-option v-for="dict in auditStatusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="审核意见" prop="auditComment">
            <el-input v-model="form.auditComment" type="textarea" placeholder="" />
          </el-form-item>
          <el-divider content-position="center">生产计划明细信息</el-divider>
          <el-table :data="mesProductPlanDetailList" :row-class-name="rowMesProductPlanDetailIndex" ref="detailTableRef">
            <el-table-column label="序号" align="center" prop="index" width="50" />
            <el-table-column label="产品" prop="materialName" width="150" />
            <el-table-column label="型号" prop="materialModel" />
            <el-table-column label="规格" prop="materialSpecification" />
            <el-table-column label="单位" prop="materialUnit" />
            <el-table-column label="生产数量" prop="quantity" width="150">
              <template #default="scope">
                <el-form-item :prop="'mesProductPlanDetailList.'+scope.$index+'.quantity'" :rules="rules.quantity">
                  <el-input v-model.number="scope.row.quantity" placeholder="请输入生产数量" disabled />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="生产日期" prop="productDate" width="240">
              <template #default="scope">
                <el-form-item :prop="'mesProductPlanDetailList.'+scope.$index+'.productDate'" :rules="rules.productDate">
                  <el-date-picker v-model="scope.row.productDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择生产日期" disabled />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button v-if="form.applyStatus!='2'" type="primary" @click="submitForm('1')">通 过</el-button>
            <el-button v-if="form.applyStatus!='2'" type="warning" @click="submitForm('0')">驳 回</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Search, Refresh, Edit } from '@element-plus/icons-vue'
  import { parseTime } from '@/utils/ruoyi'
  import { getDicts } from '@/api/system/dict/data'
  import { selectDictLabel } from '@/utils/ruoyi'
  import useUserStore from '@/store/modules/user'
  import {
    listProductPlan4Audit,
    getProductPlan,
    auditProductPlan
  } from "@/api/mesPlan/productPlan"
  
  // refs
  const queryFormRef = ref()
  const formRef = ref()
  const detailTableRef = ref()
  
  // 状态数据
  const loading = ref(true)
  const ids = ref([])
  const showSearch = ref(true)
  const total = ref(0)
  const open = ref(false)
  const orderSelectOpen = ref(false)
  const title = ref('')
  
  // 选项数据
  const projectIdOptions = ref([])
  const applyUserOptions = ref([])
  const applyStatusOptions = ref([])
  const auditUserOptions = ref([])
  const auditStatusOptions = ref([])
  
  // 列表数据
  const productPlanList = ref([])
  const mesProductPlanDetailList = ref([])
  
  // 日期范围
  const daterangeDeliveryDate = ref([])
  const daterangeApplyTime = ref([])
  const daterangeAuditTime = ref([])
  
  // stores
  const userStore = useUserStore()
  
  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    orderId: null,
    serialNo: null,
    projectId: null,
    name: null,
    deliveryDate: null,
    applyUser: null,
    applyTime: null,
    applyStatus: null,
    auditUser: null,
    auditTime: null,
    auditStatus: null
  })
  
  // 表单数据
  const form = reactive({
    id: null,
    serialNo: null,
    orderId: null,
    orderNo: null,
    projectId: null,
    name: null,
    deliveryDate: null,
    applyUser: null,
    applyTime: null,
    applyStatus: null,
    auditUser: null,
    auditTime: null,
    auditStatus: null,
    auditComment: null,
    remark: null,
    mesProductPlanDetailList: []
  })
  
  // 表单验证
  const checkAuditComment = (rule, value, callback) => {
    if (form.auditStatus === '0' && !value) {
      callback(new Error('请输入审核意见'))
      return
    }
    callback()
  }
  
  const rules = {
    auditComment: [
      { validator: checkAuditComment, trigger: 'blur' },
      { max: 100, message: "审核意见最多100个字符", trigger: "blur" }
    ]
  }
  
  // 监听明细列表变化
  watch(mesProductPlanDetailList, (newVal) => {
    form.mesProductPlanDetailList = newVal
  }, { deep: true, immediate: true })
  
  // 方法
  const getList = async () => {
    loading.value = true
    try {
      const params = {
        ...queryParams,
        params: {}
      }
      if (daterangeDeliveryDate.value?.length) {
        params.params.beginDeliveryDate = daterangeDeliveryDate.value[0]
        params.params.endDeliveryDate = daterangeDeliveryDate.value[1]
      }
      if (daterangeApplyTime.value?.length) {
        params.params.beginApplyTime = daterangeApplyTime.value[0]
        params.params.endApplyTime = daterangeApplyTime.value[1]
      }
      if (daterangeAuditTime.value?.length) {
        params.params.beginAuditTime = daterangeAuditTime.value[0]
        params.params.endAuditTime = daterangeAuditTime.value[1]
      }
      const response = await listProductPlan4Audit(params)
      productPlanList.value = response.rows
      total.value = response.total
    } finally {
      loading.value = false
    }
  }
  
  // 格式化方法
  const projectIdFormat = (row) => selectDictLabel(projectIdOptions.value, row.projectId)
  const applyUserFormat = (row) => selectDictLabel(applyUserOptions.value, row.applyUser)
  const applyStatusFormat = (row) => selectDictLabel(applyStatusOptions.value, row.applyStatus)
  const auditUserFormat = (row) => selectDictLabel(auditUserOptions.value, row.auditUser)
  const auditStatusFormat = (row) => selectDictLabel(auditStatusOptions.value, row.auditStatus)
  
  // 操作方法
  const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
  }
  
  const resetQuery = () => {
    daterangeDeliveryDate.value = []
    daterangeApplyTime.value = []
    daterangeAuditTime.value = []
    queryFormRef.value?.resetFields()
    handleQuery()
  }
  
  const reset = () => {
    Object.assign(form, {
      id: null,
      serialNo: null,
      orderId: null,
      orderNo: null,
      projectId: null,
      name: null,
      deliveryDate: null,
      applyUser: null,
      applyTime: null,
      applyStatus: null,
      auditUser: null,
      auditTime: null,
      auditStatus: null,
      auditComment: null,
      remark: null,
      mesProductPlanDetailList: []
    })
    mesProductPlanDetailList.value = []
    formRef.value?.resetFields()
  }
  
  const handleUpdate = async (row) => {
    reset()
    const id = row.id || ids.value
    try {
      const response = await getProductPlan(id)
      Object.assign(form, response.data)
      mesProductPlanDetailList.value = response.data.mesProductPlanDetailList
      open.value = true
      title.value = "查看生产计划详情"
    } catch (error) {
      console.error('获取生产计划详情失败:', error)
    }
  }
  
  const submitForm = async (status) => {
    form.auditStatus = status
    try {
      await formRef.value?.validate()
      // 设置审核人为当前用户
      form.auditUser = userStore.id
      // 设置审核时间为当前时间
      form.auditTime = parseTime(new Date(), '{y}-{m}-{d}')
      await auditProductPlan(form)
      ElMessage.success("审核成功")
      open.value = false
      getList()
    } catch (error) {
      console.error('审核失败:', error)
    }
  }
  
  const cancel = () => {
    open.value = false
    reset()
  }
  
  const rowMesProductPlanDetailIndex = ({ row, rowIndex }) => {
    row.index = rowIndex + 1
  }
  
  // 初始化
  onMounted(async () => {
    try {
      const [
        projectRes,
        userRes,
        applyStatusRes,
        auditStatusRes
      ] = await Promise.all([
        getDicts("query_project"),
        getDicts("query_user"),
        getDicts("apply_status"),
        getDicts("audit_status")
      ])
  
      projectIdOptions.value = projectRes.data
      applyUserOptions.value = userRes.data
      auditUserOptions.value = userRes.data
      applyStatusOptions.value = applyStatusRes.data
      auditStatusOptions.value = auditStatusRes.data
  
      await getList()
    } catch (error) {
      console.error('初始化失败:', error)
    }
  })
  </script>